package com.pubinfo.passbook.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class SessionCookieUtils {
  
  public static HttpServletRequest getHttpServletRequest() {
    //获取request、response、session
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (requestAttributes != null) {
      return requestAttributes.getRequest();
    }
    return null;
  }
  
  public static void clearCookieAll() {
    clearCookieAll(getHttpServletRequest());
  }
  
  public static void clearCookieAll(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
      for (Cookie cookie : cookies) {
        cookie.setMaxAge(0);
      }
    }
  }
  
  public static String getCookie(HttpServletRequest request, String cookieName) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0 && StringUtils.isNotBlank(cookieName)) {
      for (Cookie cookie : cookies) {
        if (cookieName.equals(cookie.getName())) {
          return cookie.getValue();
        }
      }
    }
    return null;
  }
}
